from flask import Flask, request, jsonify,render_template
from flask_cors import CORS
import requests,json
app = Flask(__name__)
CORS(app)  # 允许跨域请求

@app.route('/')
def index():
   return render_template('index.html')

@app.route('/chat/', methods=['POST'])
def chat():
    data = request.get_json()

    if not data or 'message' not in data:
        return jsonify({"error": "No message found"}), 400

    # 提取 message 参数
    message = data.get('message')

    val = langflow(message)
    print(val)
    # 返回 JSON 响应
    response = {
        "message": val
    }

    return jsonify(response), 200  # 返回 JSON 响应和状态码 200


def langflow(input_text):
   url = "http://192.168.31.122:7960/api/v1/run/ragtest02"
   headers = {"Content-Type": "application/json"}

   data = {
      "input_value": input_text,
      "output_type": "chat",
      "input_type": "chat",
      "tweaks": {
         "Prompt-tVM2Q": {
            "template": "已知信息:\n{context}\n\n用户问：\n{query}",
            "context": "",
            "query": ""
         },
         "ChatInput-z20Ux": {
            "files": "",
            # "input_value": "霍因有几台服务器",
            "sender": "User",
            "sender_name": "User",
            "session_id": "",
            "should_store_message": True
         },
         "Chroma-HVzdt": {
            "allow_duplicates": False,
            "chroma_server_cors_allow_origins": "",
            "chroma_server_grpc_port": None,
            "chroma_server_host": "",
            "chroma_server_http_port": None,
            "chroma_server_ssl_enabled": False,
            "collection_name": "sun02",
            "limit": None,
            "number_of_results": 10,
            "persist_directory": "sun02",
            "search_query": "",
            "search_type": "Similarity"
         },
         "OllamaEmbeddings-qR3Z2": {
            "base_url": "http://localhost:11434",
            "model": "smartcreation/bge-large-zh-v1.5:f16",
            "temperature": 0.1
         },
         "ParseData-OCisO": {
            "sep": "\n",
            "template": "{text}"
         },
         # "TextOutput-j5JSy": {
         #     "input_value": ""
         # },
         "ChatTongyi-qkTiC": {
            # "input_value": "",
            "model": "qwen-turbo",
            "stream": False,
            "system_message": "",
            "temperature": 0.95,
            "tongyi_sk": "sk-031954fbed5c4d2f86e486a6cac7162f",
            "top_p": 0.8
         }
      }
   }

   # 5、发送post请求进行测试
   response = requests.post(url, headers=headers, data=json.dumps(data))
   # 检查响应状态码
   if response.status_code == 200:
      try:
         # logger.info(f"输出响应内容是: {response.status_code}\n")
         # logger.info(f": {response.json()}\n")
         # 解析具体回复的内容
         # content = response.json()['outputs'][0]['outputs'][0]['results']['message']['data']['text']  #本地大模型格式
         content = response.json()['outputs'][0]['outputs'][0]['results']['text']['data']['text']  # 通义访问API的格式


         print(f"输出响应内容是: {content}\n")
         return content
      except requests.exceptions.JSONDecodeError:
         # 响应不是JSON格式
         print("Response content is not valid JSON")
   else:
      print(f"Request failed with status code {response.status_code}")


if __name__ == '__main__':
    app.run()
